import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '../pages/Dashboard.vue'
import Materials from '../pages/Materials.vue'
import Customers from '../pages/Customers.vue'
import Orders from '../pages/Orders.vue'
import Reports from '../pages/Reports.vue'
import Login from '../pages/Login.vue'
import { restoreAuth, http } from '../api/http'
import { useAuthStore } from '../store/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/dashboard' },
    { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
    { path: '/materials', component: Materials, meta: { requiresAuth: true } },
    { path: '/customers', component: Customers, meta: { requiresAuth: true } },
    { path: '/orders', component: Orders, meta: { requiresAuth: true } },
    { path: '/reports', component: Reports, meta: { requiresAuth: true } },
    { path: '/login', component: Login },
  ]
})

router.beforeEach(async (to, _from, next) => {
  restoreAuth()
  const token = localStorage.getItem('bm_auth')
  const store = useAuthStore()

  if (to.meta?.requiresAuth) {
    if (!token) return next('/login')

    if (!store.authenticated) {
      try {
        const res = await http.get('/auth/me')
        store.authenticated = !!res.data?.authenticated
        store.username = res.data?.username || store.username
        store.roles = res.data?.roles || []
        store.menus = res.data?.menus || []
        if (!store.authenticated) return next('/login')
      } catch (_) {
        return next('/login')
      }
    }

    if (to.path !== '/login' && store.menus?.length) {
      const allowed = store.menus.some(m => m.path === to.path)
      if (!allowed) return next('/dashboard')
    }
  }

  next()
})

export default router